package com.knowledge.framework.security;

/**
 * @author: zhaoyongke
 * @create: 2024-05-30 10:47
 * @description: openId
 */


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.knowledge.common.core.domain.entity.SysUser;
import com.knowledge.common.core.domain.model.LoginUser;
import com.knowledge.common.utils.SecurityUtils;
import com.knowledge.framework.web.service.SysPermissionService;
import com.knowledge.system.service.ISysUserService;
import io.jsonwebtoken.lang.Collections;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 查询手机号登录信息并封装为 UserDetails 这里可以抽取一个抽象类，权限加载和校验租户等逻辑交给父类处理
 *///
//@Service("phoneUserDetailsService")
@Slf4j
public class PhoneUserDetailsService implements UserDetailsService {
    @Resource
    private ISysUserService userService;


    @Resource
    private SysPermissionService permissionService;

    /**
     * loadUserByUsername
     *
     * @return LoginUser
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        // 直接使用手机号参数，避免JSON解析错误
        System.out.println(phone + "手机号===================");

        List<SysUser> sysUsers = userService.selectUserByPhone(phone);
        if (Collections.isEmpty(sysUsers)) {
            throw new InternalAuthenticationServiceException("手机号：" + phone + " 不存在");
        }

        return createLoginUser(sysUsers.get(0));
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }


}